<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of login
 *
 * @author Admin
 */
class login extends MY_Controller {

	public function index() {
		
		$ref = request('ref') != '' ? base_url(request('ref')) : url_create('admin');

		if (preg_match('/' . addcslashes(url_create('admin', 'login'), '/.\\*+[])(|?^') . '/i', $ref) != 0)
			$ref = url_create('admin');
		if ($this->isUserLogin())
			redirect($ref);

		if (isset($_POST['username'])) {
			$this->load->helper('form');
			$this->load->library('form_validation');

			$this->form_validation->set_rules('username', 'username', 'required');
			$this->form_validation->set_rules('password', 'password', 'required');

			if (!$this->form_validation->run()) {
				$json['state'] = 'error';
				$json['message'] = lang('login_invalid');
				echo json_encode($json);
			} else {
				$username = $this->input->post('username');
				$password = $this->input->post('password');
				$remember = $this->input->post('remember');
				if ($this->loginUser($username, $password, $remember)) {
					$json['state'] = 'success';
					$json['message'] = lang('login_success');
					echo json_encode($json);
				} else {
					$json['state'] = 'error';
					$json['message'] = lang('login_fail');
					echo json_encode($json);
				}
			}
		} else {
			$this->data['reference'] = $ref;
			$this->data['temp'] = 'admin/login/index';
			$this->load->view('admin/login/layout', $this->data);
		}
	}

	protected function loginUser($username, $password, $remember = 0) {
		$this->load->helper('user');
		return user_login($username, $password, $remember);
	}

}

?>
